package com.itrui.encrypted_transmission;

import java.io.*;

/**
 * 此类用于演示关于流的读写方法
 */
public class StreamUtils {
    /**
     * 功能：将输入流转换成byte[]
     *
     * @param is 输入流
     * @return byte数组
     * @throws Exception IO流异常
     */
    public static byte[] streamToByteArray(InputStream is) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建输出流对象
        byte[] b = new byte[1024];
        int len;

        while ((len = is.read(b)) != -1) {
            bos.write(b, 0, len);
        }

        byte[] array = bos.toByteArray();
        bos.close();
        return array;
    }

    /**
     * 功能：将InputStream转换成String
     *
     * @param inputStream 输入流
     * @return 字符串
     * @throws Exception IO流异常
     */
    public static String streamToString(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            byte[] b = new byte[10240];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, n);
            }
        } catch (Exception e) {
            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception e1) {
            }
        }
        return outputStream.toString();
    }
}
